//
//  MyViewController.m
//  LazyCat
//
//  Created by zhanshu on 15/9/7.
//  Copyright (c) 2015年 zhanshu. All rights reserved.
//

#import "MyViewController.h"
#import "MyHeaderView.h"
#import "YMHomeCell.h"
#import "MyMessViewController.h"
#import "SetViewController.h"//设置
#import "OrderViewController.h"
#import "AFNetworkHandler.h"
#import "ShopManagerVC.h"
#import "dpglViewController.h"
#import "BluetoothSetVC.h"
#import "FeWifiManHub.h"
#import "MJChiBaoZiHeader.h"
#import "OtherTypeViewController.h"
#import "CanceOrderlViewController.h"
#import "OtherController.h"
#import "ProductManagerVC.h"
#import "BusinessSchollController.h"
#import "serverViewController.h"
#import "expressViewController.h"
#import "dpglViewController.h"
#import "CaiWuManageViewController.h"
#import "detailWebViewController.h"
#import "LifeViewController.h"
//改版
#import "ProductManagerViewController.h"

#import "LazyCartViewController.h"
#import "MyCommunity.h"

@interface MyViewController ()<UITableViewDataSource,UITableViewDelegate,UIAlertViewDelegate> {
    NSArray *titleArr;
    NSArray *imgArr;
    NSArray *placeArr;
    NSDictionary *dataDic;
    NSString *updateURL;//版本更新地址
    FeWifiManHub *_loading;
    
}
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) MyHeaderView *headerView;
@property (nonatomic) BOOL doHaveNotReadMess;//是否有未读信息
@property (nonatomic, strong) BaseTabBarViewController *tabBar;

@end

@implementation MyViewController
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    _doHaveNotReadMess = [AppData share].doLogin;
 
    if (![[ShopCommonModel share].shopname isEqualToString:@""]) {
        [_headerView.headerImg sd_setImageWithURL:[NSURL URLWithString:[[ShopCommonModel share].shoplogo safeString]] placeholderImage:[UIImage imageNamed:@"touxiang.png"]];
        // 账户余额
        _headerView.userName.text = [ShopCommonModel share].shopname; // 懒猫社长三星路
        _headerView.shopUserLable.text = [ShopCommonModel share].username; // 社长：Jikee
        _headerView.yueLable.text = [ShopCommonModel share].cashbalance; // 账户余额
        _headerView.shouruLable.text = [ShopCommonModel share].totalincome; // 累计收入
        _headerView.todayOrder.text = [ShopCommonModel share].todayorderscount; // 今日订单个数
        _headerView.waitSend.text = [ShopCommonModel share].unfilledorderscount; // 代发货
        _headerView.addUserLable.text = [ShopCommonModel share].yesterdaynewuserscount; // 昨日新增用户

    }else{
    _headerView.userName.text = @""; // 懒猫社长三星路
    _headerView.shopUserLable.text = @""; // 社长：Jikee
    _headerView.yueLable.text = @"0.00"; // 账户余额
    _headerView.shouruLable.text = @"0.00"; // 累计收入
    _headerView.todayOrder.text = @"0"; // 今日订单个数
    _headerView.waitSend.text = @"0"; // 代发货
    _headerView.addUserLable.text = @"0"; // 昨日新增用户
    _headerView.headerImg.image = [UIImage imageNamed:@"touxiang"];
    }
    
    
    if (kNetworkNotReachability) { // 没网
        [_loading dismiss];
        
    }
}
- (void)addRefresh {
//    MJChiBaoZiHeader *header = [MJChiBaoZiHeader headerWithRefreshingBlock:^{
    
//        [header beginRefreshing];
        [self getData];
         [self  performSelector:@selector(hidlodingAction) withObject:nil afterDelay:10];
        
//    }];
//    self.tableView.header = header;
//    header.lastUpdatedTimeLabel.hidden = YES;
}
-(void)hidlodingAction
{
    [_loading dismiss];
    [_loading removeFromSuperview];
    [self.tableView.header endRefreshing];
}

-(void)getData
{
    if (kNetworkNotReachability) { // 没网
         [self.tableView.header endRefreshing];
//        return;
       
    }
    if (![AppData share].doLogin) {
        [self loginFirst];
    }
   
    NSString *url = [NSString stringWithFormat:indexUrl,[AppData share].username,[AppData share].username];
    dataDic = [NSDictionary dictionary];
    [AFNetworkHandler GETWithAFNByURL:url completion:^(id result) {
        dataDic = result;
      
        if ([dataDic[@"r"] isEqualToString:@"T"]) {
            /**
             "username": "lanmao0823",
             "shopname": "懒猫社长-国际华城体验店",
             "shoplogo": "http://admintest.ivpin.com/uploads/MallShop/ec561f66-f5dd-45dd-8a84-45f917989ae3.jpg",
             "cashbalance": "6125.42",   //账户余额
             "totalincome": "0.00",      //累计收入
             "todayorderscount": "0",    //今天订单总数
             "unfilledorderscount": "0",  //待发货订单数
             "yesterdaynewuserscount": "0",//昨天新增用户总数
             "noreadnoticecount": "0"   //未读消息总数

             **/
            [ShopCommonModel share].username = dataDic[@"username"];
            [ShopCommonModel share].shopname = dataDic[@"shopname"];
            [ShopCommonModel share].shoplogo = dataDic[@"shoplogo"];
            [ShopCommonModel share].cashbalance = dataDic[@"cashbalance"];
            [ShopCommonModel share].totalincome = dataDic[@"totalincome"];
            [ShopCommonModel share].todayorderscount = dataDic[@"todayorderscount"];
            [ShopCommonModel share].unfilledorderscount = dataDic[@"unfilledorderscount"];
            [ShopCommonModel share].yesterdaynewuserscount = dataDic[@"yesterdaynewuserscount"];
            [ShopCommonModel share].noreadnoticecount = dataDic[@"noreadnoticecount"];
            
            
            
            
            if ([dataDic[@"noreadnoticecount"] floatValue] > 0) { // 是否有未读消息
                //[AppData share].baseTabVC.redLable.hidden = NO;
                _redLable.hidden = NO;
            }else{
                //[AppData share].baseTabVC.redLable.hidden = YES;
                _redLable.hidden = YES;
            }
           [self resetUserMess]; // 头部信息显示
        }else{
//            [[MessShowView share] showWithMess:dataDic[@"m"]];
        }
        [_loading dismiss];
        [_loading removeFromSuperview];
         [self.tableView.header endRefreshing];
    }];
    [self.tableView.header endRefreshing];
}

//修改状态栏的颜色
-(UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}
#pragma mark - 头部信息
- (void)resetUserMess {
 
        if (![AppData share].doLogin) {
            _headerView.userName.text = @""; // 懒猫社长三星路
            _headerView.shopUserLable.text = @""; // 社长：Jikee
            _headerView.yueLable.text = @""; // 账户余额
            _headerView.shouruLable.text = @""; // 累计收入
            _headerView.todayOrder.text = @""; // 今日订单个数
            _headerView.waitSend.text = @""; // 代发货
            _headerView.addUserLable.text = @""; // 昨日新增用户
            [_headerView.headerImg setImageWithURL:[NSURL URLWithString:[[AppData share].img safeString]] placeholderImage:[UIImage imageNamed:@"touxiang"]];
        }else {
         
             [_headerView.headerImg sd_setImageWithURL:[NSURL URLWithString:[[ShopCommonModel share].shoplogo safeString]] placeholderImage:[UIImage imageNamed:@"touxiang.png"]];
            // 账户余额
                _headerView.userName.text = [ShopCommonModel share].shopname; // 懒猫社长三星路
                _headerView.shopUserLable.text = [ShopCommonModel share].username; // 社长：Jikee
                _headerView.yueLable.text = [ShopCommonModel share].cashbalance; // 账户余额
                _headerView.shouruLable.text = [ShopCommonModel share].totalincome; // 累计收入
                _headerView.todayOrder.text = [ShopCommonModel share].todayorderscount; // 今日订单个数
                _headerView.waitSend.text = [ShopCommonModel share].unfilledorderscount; // 代发货
                _headerView.addUserLable.text = [ShopCommonModel share].yesterdaynewuserscount; // 昨日新增用户
        }
 
}
- (void)viewDidLoad {
    [super viewDidLoad];
 
//    [self initNav:@"我的" doBack:NO];
 
    self.view.backgroundColor = BackColor;
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    _headerView = [[[NSBundle mainBundle] loadNibNamed:@"MyHeaderView" owner:self options:nil] firstObject];
    _tableView.tableHeaderView = _headerView;
    _tableView.backgroundColor = BackColor;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.showsVerticalScrollIndicator = NO;
    [self resetUserMess];
    
    _tableView.header = [MJDIYHeader headerWithRefreshingTarget:self refreshingAction:@selector(addRefresh)];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(goLoginView) name:@"PopLoginView" object:nil];
    
     [self  performSelector:@selector(getVersionMessg) withObject:nil afterDelay:2];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(tongzhi:) name:@"tongzhi" object:nil];
    
    [self loginFirst];
    
    
    
}
#pragma mark - 收到推送通知
- (void)tongzhi:(NSNotification *)text{
    
//    [AppData share].baseTabVC.redLable.hidden = NO;
//    NSLog(@"%@",text.userInfo[@"textOne"]);
//    NSLog(@"%@",text.userInfo[@"textTwo"]);
//    NSLog(@"－－－－－接收到通知------");
    
}

- (void)loginFirst {
    NSString *name = [NSUserDefualManager getValueByKey:UserName];
    NSString *psw = [NSUserDefualManager getValueByKey:Psw];


    [_loading removeFromSuperview];
    _loading = [[FeWifiManHub alloc] initWithView:self.view withMode:FeWifiManHubModeOnlyLoader];
 
    [self.view addSubview:_loading];
    [_loading show];
    
//    NSString *cid = [ NSUserDefualManager getValueByKey:@"cid"];
//    NSLog(@"=-----%@",cid);
    
    NSUserDefaults *userDefaul = [NSUserDefaults standardUserDefaults];
    NSString *cid = [userDefaul objectForKey:@"cid"];
    
    //    NSString *cid = [NSUserDefualManager getValueByKey:@"cid"];
    NSLog(@"=-----%@",cid);
    
    NSString *url = [NSString stringWithFormat:businessLoginUrl,name,psw,cid];
    [AFNetworkHandler GETWithAFNByURL:url completion:^(id result) {
        NSDictionary *dic = result;
        /**
         *  saleOrLanmao..
         */
        NSString *isLanmao = dic[@"islanmao"];
        if ([isLanmao isEqualToString:@"0"]) {//批发..
            NSLog(@"批发平台1");
        }else
        {//商家版
            NSString *r = dic[@"r"];
            if ([r isEqualToString:@"T"]) {
                NSDictionary *userMess = dic[@"shopinfo"];
                NSDictionary *userMess111 = dic[@"scoreinfo"];
                
                NSArray *communityArrs = userMess[@"communitys"];
                NSMutableArray *communityNameArs = [NSMutableArray array];
                communityNameArs = [MyCommunity mj_objectArrayWithKeyValuesArray:communityArrs];
                [AppData share].communityArrs = [communityNameArs mutableCopy];
                
                /***********懒猫掌柜****************/
                [AppData share].doLogin = YES;
                [AppData share].mobile = userMess[@"mobile"];
                [AppData share].username = userMess[@"username"];
                [AppData share].shoplogo = userMess[@"shoplogo"];
                [AppData share].shopname = userMess[@"shopname"];
                [AppData share].contacter = userMess[@"contacter"];
                [AppData share].shortintroduce = userMess[@"shortintroduce"];
                [AppData share].shopnote = userMess[@"shopnote"];
                [AppData share].openingend = userMess[@"openingend"];
                [AppData share].openingstart = userMess[@"openingstart"];
                [AppData share].serveramount = userMess[@"serveramount"];
                [AppData share].minSentamount = userMess[@"minSentamount"];
                [AppData share].privatekey = userMess[@"privatekey"];
                
                
                [AppData share].totalincome = userMess111[@"totalincome"];
                [AppData share].cashbalance = userMess111[@"cashbalance"];
                
                [NSUserDefualManager storageValue:@"1" forKey:@"doLogin"];
                [[AppData share].baseTabVC theShoppingCartCount:userMess[@"shopcart"]];
                
                [self getData];
            }else {
                LoginViewController *loginVC = [[LoginViewController alloc]init];
                [self presentViewController:loginVC animated:YES completion:^{
                    
                }];
                
            }
            
        }
    }];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 4;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 100;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
 
    return 0.01;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (section == 1) {
        return 0.01;
    }else{
        return 0.01;
    }
    
}
#pragma mark - tableView显示内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    YMHomeCell *cell = [tableView dequeueReusableCellWithIdentifier:@"homecell"];

    if (!cell) {
        cell = [[NSBundle mainBundle]loadNibNamed:@"YMHomeCell" owner:self options:nil][0];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
//    cell.delegate = self;
    [cell setHomeCellBlock:^(YMHomeCell *cell, UIButton *btn) {
        [self tableViewCell:cell btn:btn];
    }];
    if (indexPath.row == 0) {
        cell.imageViewL.image = [UIImage imageNamed:@"dingdan_new"];
        cell.imageViewM.image = [UIImage imageNamed:@"tuihuo_new"];
        cell.imageViewR.image = [UIImage imageNamed:@"shangpin_new"];
   
        cell.labelL.text = @"订单管理";
        cell.labelM.text = @"退货管理";
        cell.labelR.text = @"商品管理";
 
    }else if (indexPath.row == 1){
        cell.imageViewL.image = [UIImage imageNamed:@"dianpu_new"];
        cell.imageViewM.image = [UIImage imageNamed:@"yingxiao_new"];
        cell.imageViewR.image = [UIImage imageNamed:@"kehu_new"];
        
        cell.labelL.text = @"店铺管理";
        cell.labelM.text = @"营销工具";
        cell.labelR.text = @"客户管理";
 
    }else if (indexPath.row == 2){
        cell.imageViewL.image = [UIImage imageNamed:@"caiwu_new"];
        cell.imageViewM.image = [UIImage imageNamed:@"shangxueyuan_new"];
        cell.imageViewR.image = [UIImage imageNamed:@"tongji_new"];
        
        cell.labelL.text = @"财务管理";
        cell.labelM.text = @"商学院";
        cell.labelR.text = @"数据统计";
 
    }else if (indexPath.row == 3){
        cell.imageViewL.image = [UIImage imageNamed:@"kuaidi_new"];
        cell.imageViewM.image = [UIImage imageNamed:@"xiaoxi_new"];
        
        cell.labelL.text = @"快递服务";
        cell.labelM.text = @"消息";
        
        _redLable = [[UILabel alloc] initWithFrame:CGRectMake((ScreenWidth/2.0)+14, 20, 6, 6)];
        _redLable.backgroundColor = [UIColor redColor];
        _redLable.layer.cornerRadius = 3;
        _redLable.layer.masksToBounds = YES;
        _redLable.hidden = YES;
        [cell.contentView addSubview:_redLable];
        
    }
    cell.labelL.font = [UIFont systemFontOfSize:14];
    cell.labelM.font = [UIFont systemFontOfSize:14];
    cell.labelR.font = [UIFont systemFontOfSize:14];
 

    return cell;
}
-(void)tableViewCell:(YMHomeCell *)cell btn:(UIButton *)btn
{
    NSIndexPath *indexPath = [_tableView indexPathForCell:cell];
    NSInteger tag = btn.tag;
    
    if (indexPath.row == 0) {
        if (tag == 99) { // 订单管理
            OrderViewController *order = [[OrderViewController alloc] init];
            [self.navigationController pushViewController:order animated:YES];
        }else if (tag == 101){ // 退货管理
            OrderViewController *order = [[OrderViewController alloc]init];
            order.tuiHuoManager = YES;
            [self.navigationController pushViewController:order animated:YES];
            
        }else if (tag == 102){// 产品管理
            ProductManagerViewController *product = [[ProductManagerViewController alloc]init];
            [self.navigationController pushViewController:product animated:YES];
        }
    }else if (indexPath.row == 1){
        if (tag == 99) {// 店铺管理
            ShopManagerVC *shop = [[ShopManagerVC alloc] init];
            [self.navigationController pushViewController:shop animated:YES];
        }else if (tag == 101){//营销工具
            dpglViewController *dpgl = [[dpglViewController alloc] init];
            [self.navigationController pushViewController:dpgl animated:YES];
        }else if (tag == 102){//客户管理
            serverViewController *clientVC = [[serverViewController alloc]init];
            NSUserDefaults *userDefaul = [NSUserDefaults standardUserDefaults];
            NSString *iptype = [userDefaul objectForKey:@"iptype"];
            NSString *banben = [userDefaul objectForKey:@"banben"];
            NSString *url = [NSString stringWithFormat:serverManagerUrl,[AppData share].username,[Utils md5SignStr],iptype,banben];
            clientVC.requestUrl = url;
            [self.navigationController pushViewController:clientVC animated:YES];
        }
    }else if (indexPath.row == 2){
        if (tag == 99) {//财务管理
            CaiWuManageViewController *caiwu = [[CaiWuManageViewController alloc] init];
            [self.navigationController pushViewController:caiwu animated:YES];
            
        }else if (tag == 101){ // 商学院
            BusinessSchollController *business = [[BusinessSchollController alloc] init];
            business.keyword = @"";
            [self.navigationController pushViewController:business animated:YES];
        }else if (tag == 102){//数据统计
            detailWebViewController *detailWebVC = [[detailWebViewController alloc]init];
            [self.navigationController pushViewController:detailWebVC animated:YES];
        }
    }else if (indexPath.row == 3){
        if (tag == 99) {//快递服务
            expressViewController *clientVC = [[expressViewController alloc]init];
            NSUserDefaults *userDefaul = [NSUserDefaults standardUserDefaults];
            NSString *iptype = [userDefaul objectForKey:@"iptype"];
            NSString *banben = [userDefaul objectForKey:@"banben"];
            NSString *url = [NSString stringWithFormat:KDManagerUrl,[AppData share].username,[Utils md5SignStr],iptype,banben];
            clientVC.requestUr = url;
            [self.navigationController pushViewController:clientVC animated:YES];
        }else if (tag == 101){ // 消息
            LifeViewController *life = [[LifeViewController alloc] init];
            life.redLabel = _redLable;
            [self.navigationController pushViewController:life animated:YES];
        }else if (tag == 102){
        }
    }
 }
#pragma mark - 版本升级
- (void)getVersionMessg {
    NSString *banbenID = @"1"; // 版本号
    NSString *url = @"";
    
    if ([banbenID isEqualToString:@"1.0.1"]) { // APPStore版本升级
        
        url = [NSString stringWithFormat:Updatestore,[Utils md5SignStr],@"1.0.2"];
        [NTNetUtil sendRequestWithUrl:url requestName:UpdateVersion method:NTRequestMethodGET parameters:nil block:^(NTHttpRequest *networkRequest, NSError *error) {
            NSDictionary *dic = networkRequest.responseData;
            NSString *suc = dic[@"r"];
            if ([suc isEqualToString:@"T"]) {
                NSDictionary *ios = dic[@"IOSstore"];
                //            NSString *currentVS =  [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
                
                NSString *need = [ios[@"need"] safeString];
                NSString *note = [ios[@"note"] safeString];
                NSString *title = [ios[@"title"] safeString];
                NSString *isnew = [ios[@"isnew"] safeString];
                if ([isnew isEqualToString:@"false"]) {
                    return ;
                }
                if ([need isEqualToString:@"false"]) {
                    //不强制
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:note delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"更新", nil];
                    alert.tag = 100;
                    [alert show];
                }else {
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:note delegate:self cancelButtonTitle:@"更新" otherButtonTitles:nil, nil];
                    alert.tag = 101;
                    [alert show];
                }
                updateURL = [ios[@"url"] safeString];
            }
        }];
        
        //=======================================================================================
    }else{ // 企业版本号
        url = [NSString stringWithFormat:UpdateVersion,[Utils md5SignStr],@"1.1.0"]; // 1.0.4
        [NTNetUtil sendRequestWithUrl:url requestName:UpdateVersion method:NTRequestMethodGET parameters:nil block:^(NTHttpRequest *networkRequest, NSError *error) {
            NSDictionary *dic = networkRequest.responseData;
            NSString *suc = dic[@"r"];
            if ([suc isEqualToString:@"T"]) {
                NSDictionary *ios = dic[@"iOS"];
                //            NSString *currentVS =  [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
                
                NSString *need = [ios[@"need"] safeString];
                NSString *note = [ios[@"note"] safeString];
                NSString *title = [ios[@"title"] safeString];
                NSString *isnew = [ios[@"isnew"] safeString];
                if ([isnew isEqualToString:@"false"]) {
                    return ;
                }
                if ([need isEqualToString:@"false"]) {
                    //不强制
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:note delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"更新", nil];
                    alert.tag = 100;
                    [alert show];
                }else {
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:note delegate:self cancelButtonTitle:@"更新" otherButtonTitles:nil, nil];
                    alert.tag = 101;
                    [alert show];
                }
                updateURL = [ios[@"url"] safeString];
            }
        }];
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    if (alertView.tag == 100) {
        if (buttonIndex == 1) { // 更新
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",updateURL]]];
        }
    }else {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",updateURL]]];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
